﻿using Abp.Authorization;
using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Mvc;
using shenghua.Authorization;
using shenghua.Common.Dto;
using shenghua.Marketing.SalesPromotions.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Marketing.SalesPromotions
{
    [AbpAuthorize(PermissionNames.SalesPromotionManagement)]
    public class SalesPromotionAppService: shenghuaAppServiceBase, ISalesPromotionAppService
    {
        private readonly SalesPromotionManager _salesPromotionManager;
        private readonly IRepository<SalesPromotion> _salesPromotionRepository;

        public SalesPromotionAppService(
            SalesPromotionManager salesPromotionManager,
            IRepository<SalesPromotion> salesPromotionRepository
            )
        {
            _salesPromotionManager = salesPromotionManager;
            _salesPromotionRepository = salesPromotionRepository;
        }

        public async Task<SalesPromotionDto> Create(CreateSalesPromotionDto input)
        {
            var item = new SalesPromotion();
            input.MapTo(item);

            await _salesPromotionManager.Create(item);
            return new SalesPromotionDto(item);
        }

        public async Task<SalesPromotionDto> Update(UpdateSalesPromotionDto input)
        {
            var item = await _salesPromotionManager.Get(input.Id);
            input.MapTo(item);

            await _salesPromotionManager.Update(item);
            return new SalesPromotionDto(item);
        }

        [HttpPost]
        public async Task Delete(BatchIntIdDto input)
        {
            foreach(int id in input.Ids)
            {
                await _salesPromotionManager.Delete(id);
            }
        }

        public async Task<SearchResultDto<SalesPromotionDto>> Search(SearchSalesPromotionDto input)
        {
            var query = _salesPromotionRepository.GetAll();

            if(input.Status != null && (int)input.Status != -1)
            {
                switch(input.Status)
                {
                    case SalesPromotionStatus.PendingStart: query = query.Where(r => r.IsNotStarted); break;
                    case SalesPromotionStatus.Ongoing: query = query.Where(r => r.IsOngoing); break;
                    case SalesPromotionStatus.Finished: query = query.Where(r => r.IsFinished); break;
                }
            }

            int totalCount = query.Count();
            var items = query.OrderByDescending(r => r.CreationTime).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();

            return new SearchResultDto<SalesPromotionDto>
            {
                TotalCount = totalCount,
                Items = items.Select(r => new SalesPromotionDto(r)).ToList()
            };
        }
    }
}
